export default class Matrix {
  #data = [];

  size = 1;

  constructor(size) {
    this.size = size;
    for (let i = 0; i < size; i++) {
      this.#data.push(new Array())
      for (let j = 0; j < size; j++) {
        this.#data[i].push(new Array())
      }
    }
  }

  getLegalIndex(n) {
    let temp = n
    if (n < 0) {
      temp = this.size - Math.abs(n) % this.size
    }
    if (n >= this.size) {
      temp = Math.abs(n) % this.size
    }
    return temp
  }

  get(x, y) {
    return this.#data[this.getLegalIndex(x)][this.getLegalIndex(y)];
  }

  set(x, y, value) {
    if (value === undefined) {
      throw new Error("值不能为undefined")
    }
    const lx = this.getLegalIndex(x), ly = this.getLegalIndex(y)
    if (typeof value === 'function') {
      this.#data[lx][ly] = value(this.#data[lx][ly])
    } else {
      this.#data[lx][ly].push(value);
    }
    return [lx, ly]
  }

  // 获取一个二层深拷贝的转置矩阵
  transposed() {
    const tempArr = [...this.#data.map((val) => [...val])]
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < i; j++) {
        const tmp = tempArr[i][j];
        tempArr[i][j] = tempArr[j][i];
        tempArr[j][i] = tmp;
      }
    }
    return tempArr
  }

  get data() {
    return this.#data
  }

  get value() {
    let lines = [];
    const transposedMatrix = this.transposed()
    for (let i = 0; i < this.size; i++) {
      lines.push(`[${transposedMatrix[i].map((val) => JSON.stringify(val)).join(", ")}]`);
    }
    return lines.join(",\n")
  }
}
